package com.leetcode.No0856;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

/**
 * @program: Solution
 * @description: 括号的分数
 * @author: Wang Zhihua
 * @date: 2022-10-09
 */
public class Solution {

    private String str;

    public int scoreOfParentheses(String s) {
        str = s.replaceAll("\\(\\)", "+1");
        while (str.contains("(")) {
            addAllVal();
            doubleVal();
        }
        addAllVal();
        return Integer.parseInt(str);
    }

    private void doubleVal() {
        int len;
        int start = 0, end;
        while (true) {
            addAllVal();
            len = str.length();

            while (start < len && start + 1 < len && !(str.charAt(start) == '(' && str.charAt(start + 1) == '+')){
                ++start;
            }
            end = start;
            while (++end < len) {
                if (str.charAt(end) == '(') {
                    start = end;
                    break;
                } else if (str.charAt(end) == ')') {
                    ++end;
                    break;
                }
            }

            if (start != end && start + 1 < len && end <= len) {
                String valStr = str.substring(start + 1, end - 1);
                int val = Integer.parseInt(valStr);
                String subStr = str.substring(start, end);
                str = str.replace(new StringBuilder(subStr), String.format("+%d", val << 1));
                start = Math.max(0, start - 1);
            }

            if (end >= len) {
                break;
            }
        }
    }

    private void addAllVal() {
        int len;
        int start = -1, end;
        while (true) {
            len = str.length();

            while (++start < len && str.charAt(start) != '+'){}
            end = start;
            while (++end < len && !(str.charAt(end) == '(' || str.charAt(end) == ')')){}
            if (start != end && end <= len) {
                String subStr = str.substring(start + 1, end);
                String[] splits = subStr.split("\\+");
                int sum = 0;
                for (String num : splits) {
                    sum += Integer.parseInt(num);
                }
                str = str.replace(new StringBuilder(subStr), String.format("%d", sum));
            }

            if (end >= len) {
                break;
            }
            ++start;
        }
    }

    @Test
    public void test1() {
        String s = "()";
        System.out.println(scoreOfParentheses(s));

        s = "(())";
        System.out.println(scoreOfParentheses(s));

        s = "()()";
        System.out.println(scoreOfParentheses(s));

        s = "(()(()))";
        System.out.println(scoreOfParentheses(s));

        s = "((()))()";
        System.out.println(scoreOfParentheses(s));

        s = "((())())";
        System.out.println(scoreOfParentheses(s));
    }
}
